package com.settlement.system.common.util.common;

import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * httpclient请求工具类
 * @author he.xx
 */
public class HttpClientCommonUtil {
	private static Logger LOGGER = LoggerFactory.getLogger(HttpClientCommonUtil.class);

    /**
     * 编码格式。发送编码格式统一用UTF-8
     */
    private static final String ENCODING = "UTF-8";
    
    public static String doGet(String url) {
    	return doGet(url, null, null);
    }
    
    public static String doGet(String url, Map<String, String> paramMap) {
    	return doGet(url, null, paramMap);
    }
    
    public static String doGet(String url, Map<String, String> headerMap, Map<String, String> paramMap) {
		// 创建httpClient对象
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        HttpGet httpGet = null;
        String resultData = "";
        try {
        	httpClient = HttpClients.createDefault();
        	// 创建访问的地址
            URIBuilder uriBuilder = new URIBuilder(url);
            if (paramMap != null) {
                Set<Entry<String, String>> entrySet = paramMap.entrySet();
                for (Entry<String, String> entry : entrySet) {
                    uriBuilder.setParameter(entry.getKey(), entry.getValue());
                }
            }
            // 创建http对象
            httpGet = new HttpGet(uriBuilder.build());
            // 封装请求头
        	packageHeaders(headerMap, httpGet);
            // 执行请求
            httpResponse = httpClient.execute(httpGet);
            if (httpResponse != null && httpResponse.getEntity() != null) {
            	resultData = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
            }
        } catch (Exception e) {
        	LOGGER.error("httpPost请求异常,url="+url, e);
		} finally {
			// 释放资源
			HttpClientUtils.closeQuietly(httpResponse);
			HttpClientUtils.closeQuietly(httpClient);
		}
        return resultData;
	}
    
    public static String doPost(String url) {
    	return doPost2(url, null, "");
    }
    
    public static String doPost(String url, Map<String, String> paramMap) {
    	return doPost(url, null, paramMap);
    }
    
    public static String doPost(String url, String requestBody) {
    	return doPost2(url, null, requestBody);
    }

	public static String doPost(String url, Map<String, String> headerMap, Map<String, String> paramMap) {
		// 创建httpClient对象
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        HttpPost httpPost = null;
        String resultData = "";
        try {
        	httpClient = HttpClients.createDefault();
        	httpPost = new HttpPost(url);
            // 封装请求头
        	packageHeaders(headerMap, httpPost);
            // 添加参数
        	packageParams(paramMap, httpPost);
            // 执行请求
            httpResponse = httpClient.execute(httpPost);
            if (httpResponse != null && httpResponse.getEntity() != null) {
            	resultData = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
            }
        } catch (Exception e) {
        	LOGGER.error("httpPost请求异常,url="+url, e);
		} finally {
			// 释放资源
			HttpClientUtils.closeQuietly(httpResponse);
			HttpClientUtils.closeQuietly(httpClient);
		}
        return resultData;
	}
	
	public static String doPost2(String url, Map<String, String> headerMap, String requestBody) {
		// 创建httpClient对象
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        HttpPost httpPost = null;
        String resultData = "";
        try {
        	httpClient = HttpClients.createDefault();
        	httpPost = new HttpPost(url);
        	// 封装请求头
        	packageHeaders(headerMap, httpPost);
        	// 请求内容
            StringEntity stringEntity = new StringEntity(requestBody, "application/json", "utf-8");
		    httpPost.setEntity(stringEntity);
		    ResponseHandler<String> responseHandler = new BasicResponseHandler();
		    resultData = httpClient.execute(httpPost, responseHandler);
        } catch (Exception e) {
        	LOGGER.error("httpPost请求异常,url="+url, e);
		} finally {
			// 释放资源
			HttpClientUtils.closeQuietly(httpResponse);
			HttpClientUtils.closeQuietly(httpClient);
		}
        return resultData;
	}

    /**
     * 封装请求header
     * @param headerMap
     * @param httpRequest
     */
	public static void packageHeaders(Map<String, String> headerMap, HttpRequestBase httpRequest) {
		// 添加请求头
        if (headerMap != null) {
        	Set<Entry<String, String>> entrySet = headerMap.entrySet();
            for (Entry<String, String> entry : entrySet) {
                // 设置到请求头到HttpRequestBase对象中
            	httpRequest.setHeader(entry.getKey(), entry.getValue());
            }
        }
	}

    /**
     * 封装请求参数body
     * @param paramMap
     * @param httpPost
     * @throws UnsupportedEncodingException
     */
	public static void packageParams(Map<String, String> paramMap, HttpPost httpPost) throws UnsupportedEncodingException {
        if (paramMap != null) {
        	List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
            Set<Entry<String, String>> entrySet = paramMap.entrySet();
            for (Entry<String, String> entry : entrySet) {
            	nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            // 设置到请求的http对象中
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, ENCODING));
        }
	}




    public static String sendCPICPostRequest(String requestUrl,String jsonStr) {




        StringBuffer jsonString;
        try {
            URL url;
            url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.connect();

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            writer.write(jsonStr);
            writer.flush();
            writer.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            jsonString = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                jsonString.append(line);
            }
            br.close();
            Thread.sleep(10000);
            connection.disconnect();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return jsonString.toString();
    }
}
